import axios from 'axios'

import { openLoading, closeLoading } from './loading'
// 创建axios实例
const httpInstance = axios.create({
  baseURL: 'http://localhost:8080/',
  timeout: 5000
})


// axios请求拦截器
httpInstance.interceptors.request.use(config => {
  openLoading();
  // 如果用户登录，设置请求头 
  if (localStorage.getItem('user_token')) {
    config.headers.Authorization =  localStorage.getItem('user_token');
  }
  if(localStorage.getItem('admin_token')){
    config.headers.Authorization = localStorage.getItem('admin_token');
  }
  return config
}, e => Promise.reject(e))

// axios响应式拦截器
httpInstance.interceptors.response.use(res => {
  setTimeout(() => {
    closeLoading();
  }, 200);// 延时关闭loading
  return res.data;
}, e => {
  setTimeout(() => {
    closeLoading();
  }, 200);
  return Promise.reject(e);
})

export default httpInstance